package org.ww.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.ww.common.utils.PageUtils;
import org.ww.common.utils.Query;
import org.ww.common.utils.R;
import org.ww.product.dao.SkuInfoDao;
import org.ww.product.entity.SkuImagesEntity;
import org.ww.product.entity.SkuInfoEntity;
import org.ww.product.entity.SpuInfoDescEntity;
import org.ww.product.feign.SeckillFeignService;
import org.ww.product.service.*;
import org.ww.product.vo.SeckillSkuVo;
import org.ww.product.vo.SkuItemSaleAttrVo;
import org.ww.product.vo.SkuItemVo;
import org.ww.product.vo.SpuItemAttrGroupVo;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private AttrGroupService attrGroupService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;
    @Autowired
    private SeckillFeignService seckillFeignService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageByParams(Map<String, Object> params) {
        LambdaQueryWrapper<SkuInfoEntity> wrapper = Wrappers.lambdaQuery();

        String key = (String) params.get("key");
        if(StringUtils.isNotBlank(key)){
            wrapper.and(w -> w.eq(SkuInfoEntity::getSkuId,key).or().like(SkuInfoEntity::getSkuName,key));
        }

        String catelogId = (String) params.get("catelogId");
        if(StringUtils.isNotBlank(catelogId) && !catelogId.equals("0")){
            wrapper.eq(SkuInfoEntity::getCatalogId,catelogId);
        }

        String brandId = (String) params.get("brandId");
        if(StringUtils.isNotBlank(brandId) && !brandId.equals("0")){
            wrapper.eq(SkuInfoEntity::getBrandId,brandId);
        }

        String min = (String) params.get("min");
        if(StringUtils.isNotBlank(min)){
            wrapper.ge(SkuInfoEntity::getPrice,min);
        }

        String max = (String) params.get("max");
        if(StringUtils.isNotBlank(max) && !max.equals("0")){
            wrapper.le(SkuInfoEntity::getPrice,max);
        }

        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);

    }

    @Override
    public List<SkuInfoEntity> getByIds(List<Long> skuIds) {
        if(CollectionUtils.isEmpty(skuIds)){
            return Collections.emptyList();
        }
        return baseMapper.selectBatchIds(skuIds);
    }

    @Override
    public List<SkuInfoEntity> getBySpuId(Long spuId) {
        LambdaQueryWrapper<SkuInfoEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(SkuInfoEntity::getSpuId,spuId);
        return baseMapper.selectList(wrapper);
    }

    @Override
    public SkuItemVo item(Long skuId) throws ExecutionException, InterruptedException {
        SkuItemVo vo = new SkuItemVo();
        //1、sku基本信息获取 pms_sku_info
        CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture.supplyAsync(() -> {
            SkuInfoEntity infoEntity = getById(skuId);
            vo.setInfo(infoEntity);
            return infoEntity;
        }, threadPoolTaskExecutor);

        CompletableFuture<Void> saleAttrFuture = infoFuture.thenAcceptAsync((res) -> {
            //3、获取spu的销售属性组合
            List<SkuItemSaleAttrVo> skuItemSaleAttrVos = skuSaleAttrValueService.getSaleAttrsBySpuId(res.getSpuId());
            vo.setSaleAttr(skuItemSaleAttrVos);
        }, threadPoolTaskExecutor);

        CompletableFuture<Void> descFuture = infoFuture.thenAcceptAsync((res) -> {
            //4、获取spu的介绍
            SpuInfoDescEntity spuInfoDescEntity = spuInfoDescService.getById(res.getSpuId());
            vo.setDesc(spuInfoDescEntity);
        }, threadPoolTaskExecutor);

        CompletableFuture<Void> baseAttrFuture = infoFuture.thenAcceptAsync((res) -> {
            //5、获取spu的规格参数信息
            List<SpuItemAttrGroupVo> attrGroupVos = attrGroupService.getAttrGroupWithAttrsBySpuId(res.getSpuId(), res.getCatalogId());
            vo.setGroupAttrs(attrGroupVos);
        }, threadPoolTaskExecutor);


        //2、sku的图片信息 pms_sku_images
        CompletableFuture<Void> imagesFuture = CompletableFuture.runAsync(() -> {
            List<SkuImagesEntity> skuImagesEntities = skuImagesService.getBySkuId(skuId);
            vo.setImages(skuImagesEntities);
        }, threadPoolTaskExecutor);

        //3、查询当前商品是否处于秒杀中
        CompletableFuture<Void> seckillFuture = CompletableFuture.runAsync(() -> {
            R r = seckillFeignService.getSkuSeckillInfo(skuId);
            if(r.getCode() == 0){
                SeckillSkuVo seckillSkuVo = r.getData(new TypeReference<SeckillSkuVo>(){});
                vo.setSeckillSkuVo(seckillSkuVo);
            }
        });

        //等待所有任务都完成:
        /**
         * get()和join()方法的区别：
         * 1、get()可以设置超时时间，当业务执行时间超过指定的时间后就会抛出runtimeException，join()是不会被interrupt的，一但被执行就必须有结果
         * 2、get()的返回值是泛型T，需要进行类型转换，而join()不需要进行类型转换
         * 3、两个方法的抛出异常不同，不过抛出的异常都继承了RuntimeException
         */
        CompletableFuture.allOf(saleAttrFuture,descFuture,baseAttrFuture,imagesFuture,seckillFuture).join();

        return vo;
    }

}